package com.br.aiops.listeners;

import com.br.aiops.counter.AlertLogCounter;
import com.br.aiops.events.CountEvent;
import com.br.aiops.schedule.AbstractSchedule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class DurationListener extends AbstractListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(DurationListener.class);

    @EventListener(condition = "#event.getAlertLogCounter().getRule().getJudgeType() == 1")
    public void handlerEvent(CountEvent event) {
        LOGGER.debug("收到事件: {}", event);
        AlertLogCounter alertLogCounter = event.getAlertLogCounter();
        AbstractSchedule schedule = getSchedule(alertLogCounter.getRule().getDuration());
        schedule.count(alertLogCounter);

        //阶梯只统计不告警
        if (alertLogCounter.shouldLadderAlert()) {
            return;
        }

        //周期内没有发送过
        try {
            //保证原子性
            lock.lock();
            if (!schedule.isFlag(alertLogCounter)) {
                //近duration时间内有告警
                if (schedule.getCount(alertLogCounter) > 0) {
                    //发送告警
                    alertSender.sendAlertMessage(alertLogCounter);
                    schedule.flag(alertLogCounter);
                }
            }
        } finally {
            lock.unlock();
        }

    }
}
